#include <stdio.h>

#include "private_common.h"

void init_monitor_info_interface(struct monitor_info_interface* oper, void (*pt)(void*, void*, char*), void* ud, void* up)
{
	oper->parse_text = pt;
	oper->user_data = ud;
	oper->user_param = up;
}

void init_monitor_node(p_monitor_node ml, char* name, float thresh, uint8_t type)
{
	ml->buffer_len = 0;
	memset(&(ml->file_stat), 0, sizeof(timely_file));
	memset(ml->name, 0, MAX_LEN_NAME);
	memset(ml->buffer, 0, BUFFSIZE);
	ml->file_stat.thresh = thresh;
	sprintf(ml->name, "%s", name);
	ml->type = type;
	if (type ==1) {
		ml->oper.update = update_file_b;
	} else {
		ml->oper.update = update_file;
	}
	ml->file_stat.name = ml->name;
	ml->file_stat.buffer = ml->buffer;
	ml->file_stat.buffersize = BUFFSIZE;
}

int update_monitor_node(p_monitor_node ml)
{
	char* p;
	p = ml->oper.update(&(ml->file_stat));
	ml->buffer_len = ml->file_stat.validsize;
	if(ml->oper.parse_text) {
		ml->oper.parse_text(ml->oper.user_data, ml->oper.user_param, p);
	}
	return 0;
}

static int authorization_check()
{       
	int r = 0;
	char buffer[1024];
	FILE *fp = NULL;
	if (access("/usr/bin/dbus-send", F_OK) != 0) {
		return 0;
	}

	fp = popen("/usr/bin/dbus-send --system --print-reply --dest=com.deepin.license /com/deepin/license/Info org.freedesktop.DBus.Properties.Get  string:com.deepin.license.Info string:AuthorizationState", "r");
	if (!fp) return 0;
	fgets(buffer, sizeof(buffer), fp);
	fgets(buffer, sizeof(buffer), fp);
	sscanf(buffer, "%*s%*s%d", &r);
	return  (r == 1 || r == 3) ? 1 : 0;
}

static int system_check()
{
	FILE *fp;
	int i = 0;
	char buffer[128];
	int len;
	int flag = 0;
	char filelist[2][128] = {
		"/etc/os-release",
		"/etc/os-version"
	};
	for (i = 0;i < 2; i++) {
		if((fp = fopen(filelist[i] , "r")) == NULL) {
			continue;
		}
		while(!feof(fp)) {
			if (fgets(buffer , 128 , fp) == NULL) continue;
			len = strlen(buffer);
			if (len < 4) continue;
			if ((strncasecmp(buffer, "NAME", 4) == 0) && (strstr(buffer, "UOS") != NULL)) {
				flag = 1;
				break;
			} else if ((strncasecmp(buffer, "SystemName", 10) == 0) && (strstr(buffer, "UOS") != NULL)) {
				flag = 1;
				break;
			} else if ((strncasecmp(buffer, "PRETTY_NAME", 11) == 0) && (strstr(buffer, "UOS") != NULL)) {
				flag = 1;
				break;
			}
		}
		fclose(fp);
		if (flag) break;
	}
	return flag;
}



__attribute__((constructor)) void lib_init()
{
	if (0 == system_check()) {
		perror("It cannot run on non-UOS systems\n");
		exit(0);
	}
	if (0 == authorization_check()) {
		perror("The system is not activated.\n");
		//exit(0);
	}
}

